/* 
    Service to handle managing Todos
*/
todoApp.service("TodoService", function ($q, TodoResource) {

    this.getTodos = function () {
        var defer = $q.defer();
        TodoResource.query().$promise.then(function (returnedTodos) {
            defer.resolve(returnedTodos);
        },
            function (error) {
                defer.reject(error);
            });

        return defer.promise;
    };

    this.saveTodo = function (todo) {
        var defer = $q.defer();

        if (!isNumeric(todo.TodoId)) {
            TodoResource.save(todo, function (savedTodo) {
                defer.resolve(savedTodo);
            },
            function (error) {
                defer.reject(error);
            });
        } else {
            TodoResource.update(todo, function (savedTodo) {
                defer.resolve(savedTodo);
            },
            function (error) {
                defer.reject(error);
            });
        }

        return defer.promise;
    };

    this.deleteTodo = function (id) {
        var defer = $q.defer();
        TodoResource.delete({ todoId: id }, function () {
            defer.resolve();
        },
            function (error) {
                defer.reject(error);
            });

        return defer.promise;
    };

    function isNumeric(n) {
        return !isNaN(parseFloat(n)) && isFinite(n);
    }

});

/* 
    Service that handles to show the Error/Success messages 
*/
todoApp.service("PopupService", function () {

    this.showSuccess = function (message) {
        pop(message, 'success');
    };

    this.showError = function (message) {
        pop(message, 'error');
    };

    this.blockUi = function() {
        // Block the ui until todos are loading -> Somehow $('#spinner') or similar does not work
        $.blockUI({ message: '<h1>Loading Todos...</h1>' });
    };

    this.unBlockUi = function() {
        $.unblockUI();
    };

});


